#include "USBGPS.h"

USBGPS::USBGPS(QObject *parent) : QObject(parent)
{
    comPort = new QSerialPort;
    nmeaPosition = new QNmeaPositionInfoSource(QNmeaPositionInfoSource::RealTimeMode);
    nmeaPosition->setDevice(comPort);
    nmeaPosition->setUpdateInterval(1000);

    positionInfo = new QGeoPositionInfo;
    connect(nmeaPosition, SIGNAL(positionUpdated(QGeoPositionInfo)), this, SLOT(nmeaPositionUpdated(QGeoPositionInfo)));
    connect(nmeaPosition, SIGNAL(updateTimeout()), this, SLOT(nmeaPositionUpdateTimeOut()));
    connect(nmeaPosition, SIGNAL(error(QGeoPositionInfoSource::Error)), this, SLOT(nmeaPositionUpdateError(QGeoPositionInfoSource::Error)));
}



void USBGPS::on_acquireBtn_clicked()
{
    comPort->close();
    comPort->setBaudRate(QSerialPort::Baud4800);
    comPort->setFlowControl(QSerialPort::NoFlowControl);
    comPort->setDataBits(QSerialPort::Data8);
    comPort->setPortName(USBGPSPortname);
//    comPort->setPortName("COM4");

    comPort->setReadBufferSize(32768);

    if ( comPort->open(QIODevice::ReadOnly) == false )
        emit USBGPSPortMessage("SerialPort Open failed!");
    else
        nmeaPosition->startUpdates();
}

void USBGPS::nmeaPositionUpdated(QGeoPositionInfo posiInfo)
{
    //QDBG << "nmeaPositionUpdated" << posiInfo;
    QDateTime timeStamp = posiInfo.timestamp();
    double altitude = posiInfo.coordinate().altitude();
    double longitude = posiInfo.coordinate().longitude();
    double latitude = posiInfo.coordinate().latitude();

    emit USBGPSPort_Latitude(latitude);
    emit USBGPSPort_Longitude(longitude);
    emit USBGPSPortMessage("Posion acquired!");
}

void USBGPS::nmeaPositionUpdateTimeOut()
{
    //QDBG << "nmeaPositionUpdateTimeOut";
    emit USBGPSPortMessage("Connection TimeOut!");
}

void USBGPS::nmeaPositionUpdateError(QGeoPositionInfoSource::Error errorMsg)
{
    //QDBG << "nmeaPositionUpdateError" << errorMsg;
}

void USBGPS::on_getPositionBtn_clicked()
{
    nmeaPosition->requestUpdate(10);
}
